import { Component } from "react";
import {
    MImg,
    MSearch,
    MTool,
    MIcon,
    Popup
} from '../../components/skin/map';
import Drag from "../../components/skin/Common/Drag"
import Retrieve from '../../services/homeMap'
import {
    Layer,
    Map,
    Point,
    transformGCJ2WGS,
    Overlay
} from "../../modules/CloudMap/src/Cloud";
import {
    ModalIcon,

} from "../../modules/CloudMap/src/Components/Common";
import {
    message,
    notification
} from "antd";
const { mapData } = require("../data");
const scss = require('../../assets/styles/map.module.scss');

interface MapProps {

}
interface MapState {
    onlineCloudImgList: any[];
    imgRightIs_: boolean;
    MapObject: any[];
    currentPicture: number;
    MIconList: any[];
    listMode: any[];
    pointEditStatus: any[];
    cursorMapStyle: boolean;
    pointEditModleIs_: boolean;
    VectorSource: any;
    Icons: any;
    IconsSub: any;
    OverlayData: any;
    Overlays: any;
}

export default class MapSkin extends Component<MapProps, MapState> {
    maps: any;
    layer: any;
    timer: any;
    isSearch: any;
    constructor(props: any) {
        super(props)
        this.state = {
            onlineCloudImgList: [],
            imgRightIs_: false,
            MapObject: [],
            currentPicture: 0,
            listMode: [],
            MIconList: [],
            pointEditStatus: [false, false, false, false, false],
            cursorMapStyle: false,
            pointEditModleIs_: false,
            VectorSource: null,
            Icons: null,
            IconsSub: {
                longitude: 0,
                latitude: 0,
                text: '',
                color: '',
                url: '',
                name: '',
                data: {
                    text: {}
                }
            },
            OverlayData: {
                status: false
            },
            Overlays: null
        };
    }

    componentDidMount() {
        this.initImg();
        this.DH()
    }
    // 初始化地图参数
    initImg = () => {



        this.setState({
            onlineCloudImgList: mapData
        }, () => {
            // Initialize the cloud map
            this.layer = new Layer();
            // Create a layer object , Source configures map parameters
            let layers = this.layer.TileLayer({ Source: mapData[0] });
            // let layers1 = this.layer.TileLayer({ Source: r[1] });
            // let layers2 = this.layer.TileLayer({ Source: r[2] });
            // let layers3 = this.layer.TileCWMS({ Source: r[3] });
            // Creating a map object
            this.maps = new Map({ id: 'map', layers: [...layers] });

            this.setState({
                MapObject: layers
            })
        });


    }
    // 更新地图
    updateMap = (su: number) => {
        let { onlineCloudImgList, MapObject } = this.state;
        // remove map
        MapObject.forEach(r => {
            this.maps.removeLayer(r);
        });
        let layer = this.layer.TileLayer({ Source: onlineCloudImgList[su] });
        // add map
        layer.forEach((element: any) => {
            this.maps.addLayer(element);
        });
        // update map
        this.setState({
            MapObject: layer,
            currentPicture: su
        });
    }
    // 防抖搜索
    debounce = (value: any) => {
        let that = this;
        clearTimeout(this.timer);
        this.timer = setTimeout(function () {
            // 切换为搜索
            if (!that.isSearch) {
                that.isSearch = true;
                Retrieve.PlaceNameSearch(value, (res) => {
                    if (res.data.tips) {
                        that.setState({
                            listMode: res.data.tips
                        })
                    }
                    that.isSearch = false;
                })
            }
        }, 200);
    }

    // 地名搜索
    getSearchDetails = (value: any) => {
        this.debounce(value === null ? '' : value);
    }
    // 搜索点位跳转
    getPoint = (Source: any) => {
        const { listMode } = this.state;
        if (listMode[Source].location && typeof (listMode[Source].location) === 'string') {
            let lonlat = listMode[Source].location.split(',');
            // 高德坐标转换
            let coordinates = transformGCJ2WGS({
                lon: parseFloat(lonlat[0]),
                lat: parseFloat(lonlat[1]),
                parameter: [1.9, 3]
            });
            listMode[Source].longitude = coordinates[0];
            listMode[Source].latitude = coordinates[1];
            let Icons = Point.Icons({ Source: [listMode[Source]] });
            this.maps.addLayer(Icons);
            this.maps.getView().animate({
                center: [listMode[Source].longitude, listMode[Source].latitude],
                duration: 1000,
                zoom: 18
            });
        }

    }
    DH = () => {
        let { MIconList } = this.state;
        MIconList.push(<MIcon>er</MIcon>);
        this.setState({
            MIconList
        })
        // return <MIcon>er</MIcon>
    }
    setInputStatus = (sub: any) => {
        let status = [false, false, false, false, false];
        status[sub] = true;
        this.setState({
            pointEditStatus: status
        })
    }
    stePointStart = () => {
        this.setState({
            cursorMapStyle: true
        });
        this.getTips();
        Point.SinClick(this.maps, (f: any, p: any) => {

            this.setState({
                cursorMapStyle: false,
                pointEditModleIs_: true,
                VectorSource: f,
                Icons: p
            }, this.setPointDaultValue);
        });
    }
    setPointDaultValue = () => {
        let { Icons, IconsSub } = this.state;
        console.log(Icons);

        IconsSub.text = Icons.style_.text_.text_;
        IconsSub.longitude = Icons.geometryChangeKey_.target.flatCoordinates[0].toFixed(5);
        IconsSub.latitude = Icons.geometryChangeKey_.target.flatCoordinates[1].toFixed(5);
        this.setState({
            IconsSub
        })
    }
    /**
     * 左下角提示信息框
     */
    getTips = () => {
        notification.info({
            message: `二维地图标点`,
            description:
                '双击视觉范围内任意一点，将完成标点',
            placement: 'bottomLeft'
        });
    }
    /**
     * 实时更新图标的动态属性
     */
    setPointStyle = () => {
        let { VectorSource, Icons, IconsSub } = this.state;

        // 移除
        VectorSource.removeFeature(Icons);
        Icons.setStyle(Point.setStyle(IconsSub));
        Icons.setGeometry(Point.setGeometry(IconsSub));
        Icons.set("data", IconsSub.data);
        // 添加
        VectorSource.addFeature(Icons);
    }
    /**
     * 
     * @returns 
     * 更改点位的颜色
     */
    setColor = (e: any) => {
        let { IconsSub } = this.state;
        let sub = { ...IconsSub };
        sub.color = e;
        this.setState({
            IconsSub: sub
        }, this.setPointStyle)
    }
    /**
     * 更新点位的Name
     * @returns 
     */
    setName = (e: any) => {
        let { IconsSub } = this.state;
        let sub = { ...IconsSub };
        sub.text = e;
        this.setState({
            IconsSub: sub
        }, this.setPointStyle)
    }
    /**
     * 更新点位的图标
     * @returns 
     */
    setIcon = (e: any) => {
        let { IconsSub } = this.state;
        let sub = { ...IconsSub };
        sub.url = e;
        this.setState({
            IconsSub: sub
        }, this.setPointStyle)
    }
    /**
     * 更新点位的图标
     * @returns 
     */
    setGeometry = (e: any, type: string) => {
        let { IconsSub } = this.state;
        let sub = { ...IconsSub };
        if (type === "longitude") {
            sub.longitude = e;
        } else if (type === "latitude") {
            sub.latitude = e;
        }
        this.setState({
            IconsSub: sub
        }, this.setPointStyle)
    }
    /**
     * 更新点位的展示信息
    //  * TODO {}
     * @returns 
     */
    setPoint = (e: any, type: string) => {
        let { IconsSub } = this.state;
        let sub = { ...IconsSub };
        if (type === "text") {
            sub.data[type] = { title: sub.text, item: e };
        } else if (type === "latitude") {
            // sub.latitude = e;
        }
        this.setState({
            IconsSub: sub
        }, this.setPointStyle)
    }
    /**
    * 删除点位
   //  * TODO {}
    * @returns
    */
    deletePoint = () => {
        let { VectorSource, Icons } = this.state;
        // 移除
        VectorSource.removeFeature(Icons);
        this.setState({
            pointEditModleIs_: !this.state.pointEditModleIs_,
            pointEditStatus: [false, false, false, false, false],
            Icons: null
        });
        message.success('删除成功');
    }
    /**
    * 保存成功点位
    * TODO {}
    * @returns
    */
    savePoint = () => {
        let { Overlays } = this.state;
        this.setState({
            pointEditModleIs_: !this.state.pointEditModleIs_,
            pointEditStatus: [false, false, false, false, false]
        });
        message.success('保存成功');

        let eslect = this.maps.addInteractions('select');

        eslect.on('select', (e: any) => {
            e.target.getFeatures().clear();
            Overlays && Overlays.setPosition(undefined);
            let ll = e.selected[0].getGeometry().flatCoordinates;
            Overlays = Overlay.addCOverlay({
                id: 'POPUP',
                coordinates: [parseFloat(ll[0]).toFixed(5), parseFloat(ll[1]).toFixed(5)]
            })
            this.maps.addOverlay(Overlays);
            this.setState({
                OverlayData: {
                    status: true,
                    ...e.selected[0].get('data')
                },
                Overlays: Overlays
            })
        });
    }
    /**
     * 
     * @returns 清除点位气泡
     * 
     */
    clearOverlay = () => {
        let { Overlays } = this.state;
        Overlays.setPosition(undefined);
        this.setState({
            Overlays: null
        })
    }
    render() {
        const {
            onlineCloudImgList,
            imgRightIs_,
            listMode,
            currentPicture,
            pointEditStatus,
            cursorMapStyle,
            pointEditModleIs_,
            IconsSub,
            OverlayData
        } = this.state;
        return (
            <div className={scss['ol-admin']}>
                <div
                    id={'map'}
                    className={scss['map']}
                    style={{ cursor: cursorMapStyle ? 'crosshair' : 'default' }}
                ></div>
                {
                    pointEditModleIs_ &&
                    <Drag
                        style={{
                            width: '18vw',
                            height: '45px',
                            position: 'absolute'
                        }}
                    >
                        <ModalIcon

                            defaultValue={IconsSub}
                            setName={this.setName}
                            setIcon={this.setIcon}
                            setColor={this.setColor}
                            setPoint={this.setPoint}
                            savePoint={this.savePoint}
                            deletePoint={this.deletePoint}
                            setGeometry={this.setGeometry}
                            pointEditStatus={pointEditStatus}
                            setInputStatus={this.setInputStatus}
                        />
                    </Drag>

                }
                <MImg
                    imgList={onlineCloudImgList}
                    imgRightIs_={imgRightIs_}
                    currentPicture={currentPicture}
                    mouseGoOn={() => {
                        this.setState({
                            imgRightIs_: !imgRightIs_
                        });
                    }}
                    mouseGoOut={() => {
                        this.setState({
                            imgRightIs_: !imgRightIs_
                        });
                    }}
                    OnClick={(su) => this.updateMap(su)}
                />
                <MSearch
                    onSearch={(value) => this.getSearchDetails(value)}
                    listMode={listMode}
                    onChange={(value) => this.getSearchDetails(value.target.value)}
                    getPoint={this.getPoint}
                />
                <MTool
                    listMode={
                        <>
                            <MIcon
                                url={require('../../modules/CloudMap/src/assets/icon/point.svg').default}
                                onClick={this.stePointStart}
                            />
                        </>
                    }
                ></MTool>
                <Popup
                    OverlayData={OverlayData}
                    clearOverlay={this.clearOverlay}
                />
            </div >
        )
    }
}



